package game.leon.seawar.server;

import game.leon.engine.net.GameMessageHandler;
import game.leon.engine.net.GameSession;
import game.leon.engine.utils.Reciever;
import game.leon.engine.net.codec.GameRawMessage;
import game.leon.engine.pattern.Filter;
import game.leon.engine.utils.LinkedNode;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * User: bianpeng
 * Date: 11-12-29
 * 客户端消息接收
 */
@Component
public class MessageReceiver implements GameMessageHandler {
    private Logger logger = Logger.getLogger(getClass());
    // 立即消息队列
    private Reciever<GameMessage> gameReciever = new Reciever<GameMessage>();
    // 延时消息队列
    private Reciever<DelayMessage> delayReciver = new Reciever<DelayMessage>();
    @Autowired
    private MessageConsumer messageConsumer;
    @PostConstruct
    public void init() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                for(;;) {
                    consumeMessage();
                    consumeDelayMessage();
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        logger.error("interrupted");
                    }
                }

            }
        }).start();
    }
    //
    // 把消息吃掉
    //
    private void consumeMessage() {
        messageConsumer.consume(gameReciever.consume());
    }

    @Override
    public void execute(GameSession session, GameRawMessage message) {
        gameReciever.recieve(new GameMessage(session, message));
    }
    //
    // 添加一个延时消息
    //
    public void delay(DelayMessage message) {
        delayReciver.recieve(message);
    }
    private static class ExpiredFilter implements Filter<DelayMessage> {
        private long now = System.currentTimeMillis();
        @Override
        public boolean test(DelayMessage it) {
            return it.getExpireTime() >= now;
        }
    }
    //
    // 把过期的消息, 处理掉, 没过期的暂存着
    //
    private void consumeDelayMessage() {
        LinkedNode<DelayMessage> expired = delayReciver.consume(new ExpiredFilter());
        messageConsumer.consumeDelay(expired);
    }
}
